package com.bbcare.followup.plat.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import com.bbcare.comm.*;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import com.bbcare.department.plat.entity.DepartmentBasic;
import com.bbcare.department.plat.service.IDepartmentBasicService;
import com.bbcare.followup.plat.entity.FollowQueue;
import com.bbcare.followup.plat.entity.Patient;
import com.bbcare.followup.plat.entity.PtEvaluationGuide;
import com.bbcare.followup.plat.entity.PtEvaluationResult;
import com.bbcare.followup.plat.service.IFamilyReportService;
import com.bbcare.followup.plat.service.IFollowEvaluationScoreService;
import com.bbcare.followup.plat.service.IFollowEvaluationService;
import com.bbcare.followup.plat.service.IFollowQueueService;
import com.bbcare.followup.plat.service.IPatientInfoHisService;
import com.bbcare.followup.plat.service.IPatientService;
import com.bbcare.followup.plat.store.ibatis.IPatientDAO;

/**
 * @name: app问卷评估
 * @author: DemonLee
 * @createTime: 2017.5.12
 * @description:
 * @modify:
 *
 */
@Controller
@RequestMapping("/webapi/service")
public class AppEvaluationController {
    private final Log logger = LogFactory.getLog(AppEvaluationController.class);

    @Autowired
    private IPatientService patientService;

    @Autowired
    private IPatientInfoHisService patientInfoHisService;

    @Autowired
    private IFollowEvaluationService followEvaluationService;

    @Autowired
    private IFollowEvaluationScoreService followEvaluationScoreService;

    @Autowired
    private IDepartmentBasicService deparmentBasicService;

    @Autowired
	IPatientDAO patientdao;

    @Autowired
    IFamilyReportService familyReportService;

    @Autowired
    private IFollowQueueService fllowQueueService;



    //月度评估问卷获取
    @ResponseBody
    @RequestMapping("/evaluation/monthly/getPostion")
    public ResultModel<Object> getMonthlyPostion(@RequestBody String arg,
            HttpServletRequest request) throws Exception {
    	logger.info("in getMonthlyPostion----arg==" + arg);
        JSONObject jsonEsb = JSON.parseObject(arg);
        JSONObject requestParam = jsonEsb.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD); //统一节点处理
		if(null == requestParam){
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！");
		}
        String evaluationType = requestParam.getString("evaluationType");
        if(StringUtils.isEmpty(evaluationType)){
        	logger.info("out getMonthlyPostion----arg== null");
        	throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,"入参校验失败，评估类型不能为空");
        }

        /*channel渠道类型必传字段app登陆时特殊处理标识，跳过登陆*/
		String channel = requestParam.getString("channel");
		if(null == channel || !PropertiesUtils.getProperty("channel").equals(channel)){
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "channel传入为空或者传入值不正确!");
    	}

		String age = requestParam.getString("ageMonth");
		if(!ToolUtils.isNumeric(age)){
			logger.debug("out getMonthlyPostion----arg== null");
        	throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,"月龄不能为空,并且必须为数字");
		}

		long ageMonth =  Long.parseLong(age);
		Map<String,Object> paramsMap = new HashMap<String,Object>();

		paramsMap.put("ageMonth",ageMonth);
        if(Constants.FOLLOW_EVALUATION_PREGNANT_AHEMD.equals(evaluationType)){
			paramsMap.put("evaluationType",Constants.FOLLOW_EVALUATION_PREGNANT_AHEMD);
			//根据年龄获取题目  //app判断 还是服务端判断  3-18月限制
			if(ageMonth<3 || ageMonth>18){
				throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_AGE_OUT_RANGE,"养育环境测评只适合3月-18月的宝宝");
			}
			List<JSONObject> list  = followEvaluationService.getPregnantCommonPostion(paramsMap);
			return new ResultModel<Object>(list);
		}
		else if(Constants.FOLLOW_EVALUATION_PREGNANT_ASQ.equals(evaluationType)){
			//乐慧 暂时1-18   后续 1-60
			paramsMap.put("evaluationType",Constants.FOLLOW_EVALUATION_PREGNANT_ASQ);
			if(ageMonth<1 || ageMonth>18){
				throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_AGE_OUT_RANGE,"智能发育测评只适合1月-18月的宝宝");
			}

			List<JSONObject> list  = followEvaluationService.getPregnantCommonPostion(paramsMap);
			return new ResultModel<Object>(list);
		}
		return new ResultModel<Object>(null);
    }

    //SDQ问卷评估
    @ResponseBody
    @RequestMapping("/evaluation/getAllPostion")
    public ResultModel<Object> getAllPostion(@RequestBody String arg,
            HttpServletRequest request) throws Exception {
    	logger.info("in getAllPostion----arg==" + arg);
        JSONObject jsonEsb = JSON.parseObject(arg);
        JSONObject requestParam = jsonEsb.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD); //统一节点处理
		if(null == requestParam){
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！");
		}
        String examinationPaperName = requestParam.getString("evaluationType");
        if(StringUtils.isEmpty(examinationPaperName)){
        	logger.info("out getAllPostion----arg== null");
        	throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,"入参校验失败，examinationPaperName不能为空");
        }

        String userId = requestParam.getString("userId");
        if(StringUtils.isEmpty(userId)){
        	logger.info("out getAllPostion----arg== null");
        	throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,"入参校验失败，患者id不能为空");
        }

        /*channel渠道类型必传字段app登陆时特殊处理标识，跳过登陆*/
		String channel = requestParam.getString("channel");
		if(null == channel || !PropertiesUtils.getProperty("channel").equals(channel)){
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "channel传入为空或者传入值不正确!");
    	}

		/*String queueId = requestParam.getString("queueId");
		if(StringUtils.isEmpty(queueId)){
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "队列ID不能为空!");
    	}*/

		String deptId = requestParam.getString("deptId");
		if(StringUtils.isEmpty(deptId)){
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "随访科室ID不能为空!");
    	}

		DepartmentBasic depObj = deparmentBasicService.getDepartmentBasicDetails(deptId);
		if(null == depObj){
			throw new AppException(ErrorCode.DEPARTMENT_EXCEPTION_TYPE_DEPARTMENT_NOT_EXIST,"科室信息不存在");
		}

		//根据科室ID 查询租户ID
        Map<String,Object> ptMap = new HashMap<String,Object>();
		ptMap.put("userId",userId);
		ptMap.put("tenantId",depObj.getTenantId());
		Patient pt = patientService.getPatient(ptMap);
		if(pt == null ){
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_PATIENT_NOT_EXIST, "患者信息不存在");
		}

		Map<String,Object> paramsMap = new HashMap<String,Object>();
        if(Constants.FOLLOW_EVALUATION_PREGNANT_SDQ.equals(examinationPaperName)){
			paramsMap.put("evaluationType",Constants.FOLLOW_EVALUATION_PREGNANT_SDQ);
			paramsMap.put("Patient",pt);
			//年龄限制3岁以上  如果app用户自己修改时间 就不准
			List<JSONObject> list  = followEvaluationService.getPregnantCommonPostion(paramsMap);
			return new ResultModel<Object>(list);
		}else if(Constants.FOLLOW_EVALUATION_PREGNANT_AHEMD.equals(examinationPaperName)){
			paramsMap.put("evaluationType",Constants.FOLLOW_EVALUATION_PREGNANT_AHEMD);
			paramsMap.put("Patient",pt);
			//根据年龄获取题目  //app判断 还是服务端判断  3-18月限制
			Long birthLong=ToolUtils.getCorrect(pt.getBirthday(),pt.getPregnancyDay());//生日时间戳
//			int ageMonth = ToolUtils.getAgeMonthByBirthday(DateUtil.getDate_8(new Date()),DateUtil.getDate_8(new Date(birthLong)));
			long ageMonth=(long) ((new Date().getTime()-birthLong)/(1000*60*60*24)/30.4);
			if(ageMonth<3 || ageMonth>18){
				throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_AGE_OUT_RANGE,"养育环境测评只适合3月-18月的宝宝");
			}
			List<JSONObject> list  = followEvaluationService.getPregnantCommonPostion(paramsMap);
			return new ResultModel<Object>(list);
		}
		else if(Constants.FOLLOW_EVALUATION_PREGNANT_ASQ.equals(examinationPaperName)){
			//乐慧 暂时1-18   后续 1-60
			paramsMap.put("evaluationType",Constants.FOLLOW_EVALUATION_PREGNANT_ASQ);
			paramsMap.put("Patient",pt);

			Long birthLong=ToolUtils.getCorrect(pt.getBirthday(),pt.getPregnancyDay());//生日时间戳
			long ageMonth=(long) ((new Date().getTime()-birthLong)/(1000*60*60*24)/30.4);
			if(ageMonth<1 || ageMonth>18){
				throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_AGE_OUT_RANGE,"智能发育测评只适合1月-18月的宝宝");
			}

			List<JSONObject> list  = followEvaluationService.getPregnantCommonPostion(paramsMap);
			return new ResultModel<Object>(list);
		}else if(Constants.FOLLOW_EVALUATION_PREGNANT_SDS2.equals(examinationPaperName)) {
//			String birthday= request.getParameter("birthday");
			Map<String,Object> list = followEvaluationService.getPregnantSDS2Postion(paramsMap);
			return new ResultModel<Object>(list);
		}else if(Constants.FOLLOW_EVALUATION_PREGNANT_SAS2.equals(examinationPaperName)) {
//			String birthday= request.getParameter("birthday");
			Map<String,Object> list = followEvaluationService.getPregnantSAS2Postion(paramsMap);
			return new ResultModel<Object>(list);
		}else if(Constants.FOLLOW_EVALUATION_PREGNANT_LES.equals(examinationPaperName) ||Constants.FOLLOW_EVALUATION_PREGNANT_OSI.equals(examinationPaperName)
				||Constants.FOLLOW_EVALUATION_PREGNANT_GLE.equals(examinationPaperName)){
			paramsMap.put("examinationPaperName", examinationPaperName);
			paramsMap = followEvaluationService.getPregnantLESPostion(paramsMap);
		}
		return new ResultModel<Object>(paramsMap);
    }

	@SuppressWarnings("unchecked")
	@ResponseBody
    @RequestMapping("/evaluation/getScore")
    public ResultModel<Map<String, Object>> getScore(@RequestBody String arg,
            HttpServletRequest request) throws Exception {
    	logger.info("in getScore----arg==" + arg);
        JSONObject jsonEsb = JSON.parseObject(arg);
        JSONObject requestParam = jsonEsb.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD); //统一节点处理
		if(null == requestParam ){
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！");
		}
        String examinationPaperName = requestParam.getString("evaluationType");
        if(StringUtils.isEmpty(examinationPaperName)){
        	logger.info("out getScore----arg== null");
        	throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,"入参校验失败，examinationPaperName不能为空");
        }

        /*channel渠道类型必传字段app登陆时特殊处理标识，跳过登陆*/
		String channel = requestParam.getString("channel");
		if(null == channel || !PropertiesUtils.getProperty("channel").equals(channel)){
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "channel传入为空或者传入值不正确!");
    	}

		String queueId = requestParam.getString("queueId");
		if(StringUtils.isEmpty(queueId)){
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "队列ID不能为空!");
    	}

		String deptId = requestParam.getString("deptId");
		if(StringUtils.isEmpty(deptId)){
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "随访科室ID不能为空!");
    	}

        String userId = requestParam.getString("userId");
        if(StringUtils.isEmpty(userId)){
        	logger.info("out getAllPostion----arg== null");
        	throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,"入参校验失败，患者id不能为空");
        }
        String sourceType = requestParam.getString("sourceType");
        List<PtEvaluationGuide> guideList = new ArrayList<PtEvaluationGuide>();

        String postionIds = requestParam.getString("postionIds");
        String postionScores = requestParam.getString("postionScores");
        String taskId = requestParam.getString("taskId");
        if(StringUtils.isEmpty(postionIds)){
        	logger.info("out getScore----arg== null");
        	throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,"入参校验失败，postionIds不能为空");
        }

        DepartmentBasic depObj = deparmentBasicService.getDepartmentBasicDetails(deptId);
		if(null == depObj){
			throw new AppException(ErrorCode.DEPARTMENT_EXCEPTION_TYPE_DEPARTMENT_NOT_EXIST,"科室信息不存在");
		}
        String tenantId = depObj.getTenantId();// 租户id
        Map<String,Object> ptMap = new HashMap<String,Object>();
		ptMap.put("userId",userId);
		ptMap.put("tenantId",tenantId);
		Patient pt = patientService.getPatient(ptMap);
		if(pt == null ){
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_PATIENT_NOT_EXIST, "患者信息不存在");
		}
		Map<String,Object> paramsMap = new HashMap<String,Object>();
		String remark ="";
		//问卷结果保存入库
		PtEvaluationResult answer = new PtEvaluationResult();
		//20180410 如果没有传入testTime 取当前时间
		String testTime ="";
		if(StringUtils.isEmpty(requestParam.get("testTime"))) {
			testTime = DateUtil.getDate_8(new Date());
		}else {
			testTime = requestParam.getString("testTime");
		}
		String opCode ="";
		if(Constants.FOLLOW_EVALUATION_PREGNANT_SDQ.equals(examinationPaperName)){
			opCode = Constants.OP_CODE_1012;
			Map<String,Object> map = new HashMap<String,Object>();
			map.put("Patient",pt);
			map.putAll(requestParam);
			map.put("postionIds",postionIds);
			remark = "患者【" + pt.getUserName() + "】提交SDQ问卷测评";
			paramsMap = followEvaluationScoreService.getSDQScore(map);
		}else if(Constants.FOLLOW_EVALUATION_PREGNANT_AHEMD.equals(examinationPaperName)){
			opCode = Constants.OP_CODE_1113;
			Map<String,Object> map = new HashMap<String,Object>();
			map.put("Patient",pt);
			map.putAll(requestParam);
			map.put("postionIds",postionIds);
			remark = "患者【" + pt.getUserName() + "】提交养育环境问卷测评";
			paramsMap = followEvaluationScoreService.getAhemdScore(map);
			if(null != paramsMap.get("guideList")){
				guideList = (List<PtEvaluationGuide>)paramsMap.get("guideList");
				paramsMap.remove("guideList");
			}
		}else if(Constants.FOLLOW_EVALUATION_PREGNANT_ASQ.equals(examinationPaperName)){
			opCode = Constants.OP_CODE_1112;
			Map<String,Object> map = new HashMap<String,Object>();
			map.put("Patient",pt);
			map.putAll(requestParam);
			map.put("postionIds",postionIds);
			paramsMap = followEvaluationScoreService.getAsqScore(map);
			remark = "患者【" + pt.getUserName() + "】提交智能发育问卷测评";
			if(null != paramsMap.get("guideList")){
				guideList = (List<PtEvaluationGuide>)paramsMap.get("guideList");
				paramsMap.remove("guideList");
			}
		}else if(Constants.FOLLOW_EVALUATION_PREGNANT_SDS2.equals(examinationPaperName)||
				Constants.FOLLOW_EVALUATION_PREGNANT_SAS2.equals(examinationPaperName)){
			HashMap<String,Object> map = new HashMap<String,Object>();
			map.put("patient",pt);
			map.putAll(requestParam);
			paramsMap= followEvaluationScoreService.getYYJLScore(map);
			//同步(抑郁/焦虑)问卷数据到医院
			followEvaluationScoreService.synchroToEsb(map);
		}else if(Constants.FOLLOW_EVALUATION_PREGNANT_LES.equals(examinationPaperName)){
			Map<String,Object> map = new HashMap<String,Object>();
			map.put("patient",pt);
			map.putAll(requestParam);
			paramsMap= followEvaluationScoreService.getLESScore(map);
		}else if(Constants.FOLLOW_EVALUATION_PREGNANT_OSI.equals(examinationPaperName)){
			Map<String,Object> map = new HashMap<String,Object>();
			map.put("patient",pt);
			map.putAll(requestParam);
			paramsMap= followEvaluationScoreService.getOSIScore(map);
		}

		answer.setType(examinationPaperName);
		answer.setId(SeqUtil.getSeqNo());
		//20180410 如果没有传入createTime 取当前时间
		if(StringUtils.isEmpty(requestParam.get("createTime"))) {
			answer.setCreateTime(DateUtil.getSysDateA());
		}else {
			answer.setCreateTime(requestParam.getString("createTime"));
		}
		answer.setScore(JSON.toJSONString(paramsMap));
		if(Constants.FOLLOW_EVALUATION_PREGNANT_GLE.equals(examinationPaperName)
				||Constants.FOLLOW_EVALUATION_PREGNANT_LES.equals(examinationPaperName)
				||Constants.FOLLOW_EVALUATION_PREGNANT_OSI.equals(examinationPaperName)){
			answer.setResult(postionScores);
		}else {
			answer.setResult(postionIds);
		}
		if(StringUtils.isEmpty(sourceType)){
			answer.setSourcetype(Constants.SOURCE_TYPE_WECHAT); //APP或微信录入
		}else{
			answer.setSourcetype(sourceType); //APP或微信录入
		}

		answer.setSourceid(userId);
		answer.setTenantId(tenantId);
		answer.setUserId(userId);
		answer.setTaskId(taskId);
		answer.setTestTime(testTime);
		answer.setQueueId(queueId);
		//20180410 如果传入remark则取传入的备注
		if(!StringUtils.isEmpty(requestParam.getString("remark"))) {
			remark = requestParam.getString("remark");
		}
		answer.setRemark(remark);
		followEvaluationService.savePtEvaluationResult(answer,guideList);

		if(!Constants.FOLLOW_EVALUATION_PREGNANT_SDS2.equals(examinationPaperName)&&
				!Constants.FOLLOW_EVALUATION_PREGNANT_SAS2.equals(examinationPaperName)
				&&!Constants.FOLLOW_EVALUATION_PREGNANT_LES.equals(examinationPaperName)
				&&!Constants.FOLLOW_EVALUATION_PREGNANT_OSI.equals(examinationPaperName)){
		paramsMap.put("answerId",answer.getId());
		paramsMap.put("userName", pt.getUserName());
		paramsMap.put("userId", pt.getId());
		paramsMap.put("birthday", pt.getBirthday());
		paramsMap.put("pregnancyDay",pt.getPregnancyDay());

		Long birthLong=ToolUtils.getCorrect(pt.getBirthday(),pt.getPregnancyDay());//生日时间戳
        long ageDay = (DateUtil.getDate_8(answer.getTestTime()).getTime()-birthLong)/(1000*60*60*24);
        long ageMonth = (long) (ageDay/30.4);
		String age = ToolUtils.getCommAgeByBirthday(testTime,DateUtil.getDate_8(new Date(birthLong)));
		paramsMap.put("age",age);
		paramsMap.put("ageMonth",ageMonth+"月龄");
		//age
		paramsMap.put("testTime",testTime);
		paramsMap.put("hospName",depObj.getHospName());
		paramsMap.put("deptName",depObj.getDeptName());

		try{
			if(null != pt){
				Map<String,Object> param = new HashMap<String,Object>();
				param.putAll(requestParam);
				param.put("opUsertype",Constants.OPCODE_TYPE_PATIENT);
				param.put("type", Constants.PATIENT_ACTIVE_BUSI_TYPE_6);
				param.put("authorId",userId);
				param.put("userId",userId);
				param.put("queueId",queueId);
	            param.put("remark", remark);
				param.put("updateAccept",SeqUtil.getSeqNo());
				param.put("opCode",opCode);
				param.put("busiId",answer.getId());
				param.put("tenantId", tenantId);
				patientInfoHisService.saveOperationRecord(param);

				//诊间扫码页面集成做的评估  将记录id同步回 扫码客户端日志表
				if(Constants.PATIENT_SOURCE_TYPE_SCAN.equals(sourceType)){
					//
					Map<String,Object> synchMap = new HashMap<String,Object>();
//					synchMap.put("sourceType",Constants.PATIENT_SOURSE_TYPE_SCAN);
					synchMap.put(Constants.MQ_MESSAGE_BODY,param);
					//业务类型
					synchMap.put(Constants.MQ_MESSAGE_TYPE,Constants.CONSUMER_TYPE_EVALUATION_TO_SCAN); //问卷发到医生端  不需要区分新增和更新
					HttpUtil.postData(PropertiesUtils.getProperty("redirectUrl2"),JSON.toJSONString(synchMap));
				}
			}

		}catch(Exception e){
			logger.error("保存上传评估操作记录表报错", e);
			}
		}
//		paramsMap.put("success", true);
		return new ResultModel<Map<String,Object>>(paramsMap);
    }

	@RequestMapping("/evaluation/scorehislist")
	@ResponseBody
	public QueryModel<Map<String, Object>> getHistoryScore(@RequestBody String arg,
            HttpServletRequest request) throws Exception{
		logger.info("in getHistoryScore----arg==" + arg);
        JSONObject jsonEsb = JSON.parseObject(arg);
        JSONObject requestParam = jsonEsb.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD); //统一节点处理
		if(null == requestParam ){
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！");
		}

		 /*channel渠道类型必传字段app登陆时特殊处理标识，跳过登陆*/
		String channel = requestParam.getString("channel");
		if(null == channel || !PropertiesUtils.getProperty("channel").equals(channel)){
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "channel传入为空或者传入值不正确!");
    	}

        String userId = requestParam.getString("userId");
        if(StringUtils.isEmpty(userId)){
        	logger.info("out getHistoryScore----arg== null");
        	throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,"入参校验失败，患者ID不能为空");
        }

        String deptId = requestParam.getString("deptId");
		if(StringUtils.isEmpty(deptId)){
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "随访科室ID不能为空!");
    	}

        String type = requestParam.getString("evaluationType");
        /*if(StringUtils.isEmpty(type)){
        	logger.info("out getHistoryScore----arg== null");
        	throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,"入参校验失败，随访评测类型不能为空");
        }
*/
        List<String> typeList = new ArrayList<String>();
        if(StringUtils.isEmpty(type)){
//        	typeList.add(Constants.FOLLOW_EVALUATION_PREGNANT_AHEMD);
//          typeList.add(Constants.FOLLOW_EVALUATION_PREGNANT_ASQ);
            typeList.add(Constants.FOLLOW_EVALUATION_PREGNANT_SDQ);
        }else{
            typeList.add(type);
        }


        DepartmentBasic depObj = deparmentBasicService.getDepartmentBasicDetails(deptId);
		if(null == depObj){
			throw new AppException(ErrorCode.DEPARTMENT_EXCEPTION_TYPE_DEPARTMENT_NOT_EXIST,"科室信息不存在");
		}
        String tenantId = depObj.getTenantId();// 租户id

        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.putAll(requestParam);
        paramMap.put("userId",userId);
        paramMap.put("typeList",typeList);
        paramMap.put("tenantId", tenantId);

        paramMap.put("sourseType", Constants.SOURCE_TYPE_APP);
        List<Map<String, Object>> list= followEvaluationService.selectPtEvaluationResults(paramMap);

        int total= 0;
        if(!CollectionUtils.isEmpty(list)){
        	for(int i =0;i<list.size();i++){
        		list.get(i).remove("result");
        		list.get(i).remove("answerResult");
        	}
        	total= followEvaluationService.selectPtEvaluationResultCount(paramMap);
        }
		logger.info("out getHistoryScore----arg==" + list);
		return new QueryModel<Map<String,Object>>(list,total);
    }

	@RequestMapping("/evaluation/scoredetail")
	@ResponseBody
	public ResultModel<Map<String, Object>> getHistoryScoreDetail(@RequestBody String arg,
            HttpServletRequest request) throws Exception{
		logger.info("in getHistoryScoreDetail----arg==" + arg);
        JSONObject jsonEsb = JSON.parseObject(arg);
        JSONObject requestParam = jsonEsb.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD); //统一节点处理
		if(null == requestParam ){
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！");
		}
        /*channel渠道类型必传字段app登陆时特殊处理标识，跳过登陆*/
		String channel = requestParam.getString("channel");
		if(null == channel || !PropertiesUtils.getProperty("channel").equals(channel)){
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "channel传入为空或者传入值不正确!");
    	}

		String userId = requestParam.getString("userId");
        if(StringUtils.isEmpty(userId)){
        	logger.info("out getHistoryScoreDetail----arg== null");
        	throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,"入参校验失败，患者ID不能为空");
        }

        String evaluationId = requestParam.getString("answerId");
        if(StringUtils.isEmpty(evaluationId)){
        	logger.info("out getHistoryScoreDetail----arg== null");
        	throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,"入参校验失败，评测记录id不能为空");
        }

        String deptId = requestParam.getString("deptId");
		if(StringUtils.isEmpty(deptId)){
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "随访科室ID不能为空!");
    	}

		DepartmentBasic depObj = deparmentBasicService.getDepartmentBasicDetails(deptId);
		if(null == depObj){
			throw new AppException(ErrorCode.DEPARTMENT_EXCEPTION_TYPE_DEPARTMENT_NOT_EXIST,"科室信息不存在");
		}
        String tenantId = depObj.getTenantId();// 租户id

        Map<String,Object> ptMap = new HashMap<String,Object>();
		ptMap.put("userId",userId);
		ptMap.put("tenantId",tenantId);
		Patient pt = patientService.getPatient(ptMap);
		if(pt == null ){
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_PATIENT_NOT_EXIST, "患者信息不存在");
		}

		Map<String, Object> paramsMap = new HashMap<String, Object>();
		requestParam.put("evaluationId",evaluationId);
        Map<String, Object> resultMap= followEvaluationService.selectPtEvaluationResultDetail(requestParam);
        if(null != resultMap){
        	 String result = (String)resultMap.get("answerResult");
             String score =  (String)resultMap.get("result");

             JSONObject obj =JSON.parseObject(score);
             if(null != obj){
             	paramsMap.putAll(obj);
             }
             paramsMap.put("postionIds",JSON.parseObject(result));
             Long birthLong=ToolUtils.getCorrect(pt.getBirthday(),pt.getPregnancyDay());//生日时间戳
      		 String age = ToolUtils.getCommAgeByBirthday(resultMap.get("testTime").toString(),DateUtil.getDate_8(new Date(birthLong)));
      		 paramsMap.put("age",age);
      		 long ageDay = (DateUtil.getDate_8(resultMap.get("testTime").toString()).getTime()-birthLong)/(1000*60*60*24);
             long ageMonth = (long) (ageDay/30.4);
    		paramsMap.put("age",age);
    		paramsMap.put("ageMonth",ageMonth+"月龄");

      		 paramsMap.put("testTime",resultMap.get("testTime").toString());
        }

        paramsMap.put("userName", pt.getUserName());
        paramsMap.put("userId", pt.getId());
 		paramsMap.put("birthday", pt.getBirthday());
 		paramsMap.put("pregnancyDay",pt.getPregnancyDay());

 		paramsMap.put("hospName",depObj.getHospName());
 		paramsMap.put("deptName",depObj.getDeptName());

		logger.info("out getHistoryScore----arg==" + paramsMap);
		return new ResultModel<Map<String,Object>>(paramsMap);
    }

	@RequestMapping("/evaluation/answerdetail")
	@ResponseBody
	public ResultModel<Map<String, Object>> getAnswerDetail(@RequestBody String arg,
            HttpServletRequest request) throws Exception{
		logger.info("in getgetAnswerDetail----arg==" + arg);
        JSONObject jsonEsb = JSON.parseObject(arg);
        JSONObject requestParam = jsonEsb.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD); //统一节点处理
		if(null == requestParam ){
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！");
		}
        /*channel渠道类型必传字段app登陆时特殊处理标识，跳过登陆*/
		String channel = requestParam.getString("channel");
		if(null == channel || !PropertiesUtils.getProperty("channel").equals(channel)){
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "channel传入为空或者传入值不正确!");
    	}

		String userId = requestParam.getString("userId");
        if(StringUtils.isEmpty(userId)){
        	logger.info("out getHistoryScoreDetail----arg== null");
        	throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,"入参校验失败，患者ID不能为空");
        }

        String evaluationId = requestParam.getString("answerId");
        if(StringUtils.isEmpty(evaluationId)){
        	logger.info("out getHistoryScoreDetail----arg== null");
        	throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,"入参校验失败，评测记录id不能为空");
        }

        String deptId = requestParam.getString("deptId");
		if(StringUtils.isEmpty(deptId)){
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "随访科室ID不能为空!");
    	}

		DepartmentBasic depObj = deparmentBasicService.getDepartmentBasicDetails(deptId);
		if(null == depObj){
			throw new AppException(ErrorCode.DEPARTMENT_EXCEPTION_TYPE_DEPARTMENT_NOT_EXIST,"科室信息不存在");
		}
        String tenantId = depObj.getTenantId();// 租户id

        Map<String,Object> ptMap = new HashMap<String,Object>();
		ptMap.put("userId",userId);
		ptMap.put("tenantId",tenantId);
		Patient pt = patientService.getPatient(ptMap);
		if(pt == null ){
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_PATIENT_NOT_EXIST, "患者信息不存在");
		}

		Map<String, Object> paramsMap = new HashMap<String, Object>();
		requestParam.put("evaluationId",evaluationId);
		requestParam.put("Patient",pt);
        Map<String, Object> resultMap= followEvaluationService.getAnswerDetail(requestParam);
        if(null != resultMap){
//        	 String result = null != resultMap.get("answerResult") && ""!= resultMap.get("answerResult") ?resultMap.get("answerResult").toString():"";
//             String score =  (String)resultMap.get("result");

             Long birthLong=ToolUtils.getCorrect(pt.getBirthday(),pt.getPregnancyDay());//生日时间戳
      		 String age = ToolUtils.getCommAgeByBirthday(resultMap.get("testTime").toString(),DateUtil.getDate_8(new Date(birthLong)));
      		 paramsMap.put("age",age);
      		 paramsMap.put("answerResult", resultMap.get("answerResult"));
      		 paramsMap.put("testTime",resultMap.get("testTime").toString());
        }

        paramsMap.put("userName", pt.getUserName());
        paramsMap.put("userId", pt.getId());
 		paramsMap.put("birthday", pt.getBirthday());
 		paramsMap.put("pregnancyDay",pt.getPregnancyDay());
 		paramsMap.put("hospName",depObj.getHospName());
 		paramsMap.put("deptName",depObj.getDeptName());

		logger.info("out getHistoryScore----arg==" + paramsMap);
		return new ResultModel<Map<String,Object>>(paramsMap);
    }

	@RequestMapping("/evaluation/getGuide")
	@ResponseBody
	public ResultModel<Map<String, Object>> getGuide(@RequestBody String arg,HttpServletRequest request) throws Exception {
		logger.info("in getGuide----arg==" + arg);
        JSONObject jsonEsb = JSON.parseObject(arg);
        JSONObject requestParam = jsonEsb.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD); //统一节点处理
		if(null == requestParam ){
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！");
		}

        /*channel渠道类型必传字段app登陆时特殊处理标识，跳过登陆*/
		String channel = requestParam.getString("channel");
		if(null == channel || !PropertiesUtils.getProperty("channel").equals(channel)){
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "channel传入为空或者传入值不正确!");
    	}

		String moduleCode = requestParam.getString("moduleCode");
        if(StringUtils.isEmpty(moduleCode)){
        	logger.info("out getGuide----arg== null");
        	throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,"入参校验失败，评测模块类型不能为空");
        }

        String answerId = requestParam.getString("answerId");
        if(StringUtils.isEmpty(answerId)){
        	logger.info("out getGuide----arg== null");
        	throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,"入参校验失败，不能为空");
        }

		Map<String,Object> paramsMap = new HashMap<String,Object>();
			//aims评估结果意见 从表查询
		Map<String,Object> param = new HashMap<String,Object>();
		param.put("evaluationId",requestParam.get("answerId"));
		param.putAll(requestParam);

        Map<String, Object> resultMap= followEvaluationService.selectPtEvaluationResultDetail(param);

        if(null != resultMap){
            Map<String,Object> ptMap = new HashMap<String,Object>();
    		ptMap.put("userId",resultMap.get("userId"));
    		ptMap.put("tenantId",resultMap.get("tenantId"));
    		Patient pt = patientService.getPatient(ptMap);
    		if(pt == null ){
                throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_PATIENT_NOT_EXIST, "患者信息不存在");
    		}

    		Long birthLong=ToolUtils.getCorrect(pt.getBirthday(),pt.getPregnancyDay());//生日时间戳
            long ageDay = (DateUtil.getDate_8(resultMap.get("testTime").toString()).getTime()-birthLong)/(1000*60*60*24);
            long ageMonth = (long) (ageDay/30.4);
            String title ="";
     		String subTitle ="";
     		if(Constants.FOLLOW_EVALUATION_PREGNANT_AHEMD.equals(resultMap.get("type"))){
     			title =ageMonth+"月龄养育环境测量问卷";
     			subTitle =ageMonth+"月龄(训练指导)";
     		}else if(Constants.FOLLOW_EVALUATION_PREGNANT_ASQ.equals(resultMap.get("type"))){
     			title =ageMonth+"月龄智能发育评估问卷";
     			subTitle =ageMonth+"月龄(训练指导)";
     		}
     		paramsMap.put("title",title);
     		paramsMap.put("subTitle",subTitle);
     		paramsMap.put("ageMonth",ageMonth);
     		paramsMap.put("testTime",resultMap.get("testTime"));
     		param.put("evaluationId",requestParam.get("answerId"));
     		List<Map<String,Object>> list = followEvaluationService.getEvaluationGuides(param);
    		paramsMap.put("guideList",list);
        }else{
        	throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_TEMPERATURE_NOT_EXIST,
        			"评估记录不存在");
        }

//		paramsMap.put("success", true);
		return new ResultModel<Map<String,Object>>(paramsMap);
	}

	//查询月度评估报告
	@RequestMapping("/evaluation/workorder/report")
  	@ResponseBody
  	public ResultModel<Object> getWorkOrderReport(@RequestBody String arg,HttpServletRequest request) throws Exception {
		logger.info("in getComList----arg==" + arg);
	    JSONObject jsonEsb = JSON.parseObject(arg);
	    JSONObject requestParam = jsonEsb.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD); //统一节点处理
		if(null == requestParam ){
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！");
		}

		/*channel渠道类型必传字段app登陆时特殊处理标识，跳过登陆*/
		String channel = requestParam.getString("channel");
		if(null == channel || !PropertiesUtils.getProperty("channel").equals(channel)){
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "channel传入为空或者传入值不正确!");
	  	}

	    String workOrderId = requestParam.getString("workOrderId");
	    if (StringUtils.isEmpty(workOrderId)) {
	        throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参校验失败,订单不存在！"));
	    }

        //增加 	年龄计算类型	曲线类型	标志
        String ageType =  requestParam.getString("ageType");
        String scoreType =  requestParam.getString("scoreType");
        //如果为空则传入默认值
        if(StringUtils.isEmpty(ageType)){
        	ageType = Constants.GROWTH_AGE_TYPE_CORRECT;
        }else{
        	if(!Constants.GROWTH_AGE_TYPE_CORRECT.equals(ageType) && !Constants.GROWTH_AGE_TYPE_ACTUAL.equals(ageType)){
        		ageType = Constants.GROWTH_AGE_TYPE_CORRECT;
        	}
        }
        if(StringUtils.isEmpty(scoreType)){
        	scoreType = Constants.GROWTH_SCORE_PERCENT;
        }else{
        	if(!Constants.GROWTH_SCORE_PERCENT.equals(scoreType) && !Constants.GROWTH_SCORE_ZSCORE.equals(scoreType)){
        		scoreType = Constants.GROWTH_SCORE_PERCENT;
        	}
        }

        Map<String,Object> paramMap = new HashMap<String,Object>();
        paramMap.put("ageType", ageType);
        paramMap.put("scoreType", scoreType);
        paramMap.put("workOrderId",workOrderId);
//        paramMap.put("doctorName",doctorName);

	    Map<String,Object> retout = followEvaluationService.getWorkOrderReport(paramMap);

        return new ResultModel<Object>(retout);
  	}

	// 生长发育详情查询
	@SuppressWarnings("unchecked")
	@ResponseBody
    @RequestMapping("/growth/curvedataByValue")
    public ResultModel<Map<String, Object>> getGrowthCurvedata(@RequestBody String arg, HttpServletRequest request)
            throws Exception {
        logger.warn("in getGrowthCurvedata----arg==" + arg);

        JSONObject jsonArg = null;
        try {
            jsonArg = JSON.parseObject(arg);
        } catch (Exception ex) {
            ex.printStackTrace();
            // 后续重写异常类
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_FORMAT_ERROR, "入参节点错误，非json格式！"));
        }
        Map<String, Object> paramMap = new HashMap<String, Object>();
        JSONObject jsonData = jsonArg.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD);
        if (null == jsonData) {
            logger.warn("in getGrowthCurvedata----no data node...");
            // 前台必须传data节点，否则报错返回（后续重写异常类）
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！");
        }

        String channel = jsonData.getString("channel");
		if (null == channel || !PropertiesUtils.getProperty("channel").equals(channel)) {
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "channel传入为空或者传入值不正确!");
		}

        String queueId = jsonData.getString("queueId");
        if(StringUtils.isEmpty(queueId)){
        	logger.debug("out getGrowthCurvedata----arg== null");
        	throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,"入参校验失败，科室ID不能为空");
        }

        String userId = jsonData.getString("userId");
        if(StringUtils.isEmpty(userId)){
        	logger.debug("out getGrowthCurvedata----arg== null");
        	throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,"入参校验失败，用户ID不能为空");
        }

        Map<String,Object> parma = new HashMap<String,Object>();
        parma.put("id",queueId);
        FollowQueue depObj = fllowQueueService.getQueueDetailByQueueId(parma);
		if(null == depObj){
			throw new AppException(ErrorCode.DEPARTMENT_EXCEPTION_TYPE_DEPARTMENT_NOT_EXIST,"队列信息不存在");
		}

		String tenantId =depObj.getTenantId();

        //增加 	年龄计算类型	曲线类型	标志
        String ageType =  jsonData.getString("ageType");
        String scoreType =  jsonData.getString("scoreType");
        //如果为空则传入默认值
        if(StringUtils.isEmpty(ageType)){
        	ageType = Constants.GROWTH_AGE_TYPE_CORRECT;
        }else{
        	if(!Constants.GROWTH_AGE_TYPE_CORRECT.equals(ageType) && !Constants.GROWTH_AGE_TYPE_ACTUAL.equals(ageType)){
        		ageType = Constants.GROWTH_AGE_TYPE_CORRECT;
        	}
        }
        if(StringUtils.isEmpty(scoreType)){
        	scoreType = Constants.GROWTH_SCORE_PERCENT;
        }else{
        	if(!Constants.GROWTH_SCORE_PERCENT.equals(scoreType) && !Constants.GROWTH_SCORE_ZSCORE.equals(scoreType)){
        		scoreType = Constants.GROWTH_SCORE_PERCENT;
        	}
        }

//        Map<String,Object> valueMap =  new HashMap<String,Object>();

        paramMap.put("ageType", ageType);
        paramMap.put("scoreType", scoreType);
        paramMap.put("tenantId",tenantId);
        paramMap.put("queueId",queueId);
        paramMap.putAll(jsonData);
//        paramMap.put("doctorName",doctorName);
        String weight = jsonData.getString("hight");
        String hight = jsonData.getString("weight");
        String headCircumference = jsonData.getString("headCircumference");

        if(!StringUtils.isEmpty(weight)){
        	if(!ToolUtils.isNumeric(weight)){
    			throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "体重必须为数字！"));
        	}
        }
        if(!StringUtils.isEmpty(hight)){
        	if(!ToolUtils.isNumeric(hight)){
    			throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "身高必须为数字！"));
        	}
        }
        if(!StringUtils.isEmpty(headCircumference)){
        	if(!ToolUtils.isNumeric(headCircumference)){
    			throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "头围必须为数字！"));
        	}
        }

        String testTime = jsonData.getString("testTime");
        if(StringUtils.isEmpty(testTime)){
        	logger.debug("out getGrowthCurvedataByValue----arg== null");
        	throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,"入参校验失败，监测时间不能为空");
        }

        paramMap.put("type","true");
        paramMap.put("valueFlag","true");//按身高、体重、头围值查询
		Map<String,Object> retOut = familyReportService.getGrowthCurvedata(paramMap);

		//根据百分位level 查询生长发育指导意见
		List<String> guidelist = new ArrayList<String>();
		guidelist = familyReportService.getGrowthGuideListNew((List<Map<String, Object>>) retOut.get("curvadataList"),paramMap);
		retOut.put("guideList",guidelist);
        return new ResultModel<Map<String, Object>>(retOut);
    }
}
